package concurrency.lock;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 基于排队号的公平序列
 * @Author: hao.zhang
 * @Date: 9/6/19 11:26 AM
 */
public class SimpleTicketLock {
    private AtomicInteger serviceNum = new AtomicInteger();
    private AtomicInteger ticketNum = new AtomicInteger();

    public int lock() {
        int myTicket = ticketNum.getAndIncrement();
        while (serviceNum.get() != myTicket){
            //当前的服务号等于排队号时，表示可以获得锁
        }
        return myTicket;
    }

    public void unlock(int myTicket) {
        // 解锁时表示 服务完成，这时服务号+1
        // 如果当前排队
        serviceNum.compareAndSet(myTicket, myTicket + 1);
    }
}
